package cn.yogehaoren.agile_gateway.rnner;

import cn.yogehaoren.agile_gateway.util.K8SServiceManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * @author WangNing
 * @version 1.0
 * @date 2020/11/22 21:12
 *
 * 性能优化，初始化时就加载Service地址
 */

@Order(2)
@Component
@Slf4j
public class ServiceRunner implements ApplicationRunner {


    @Autowired
    RouteLocator  routeLocator;

    @Autowired
    K8SServiceManager k8SServiceManager;


    @Override
    public void run(ApplicationArguments args) throws Exception {

        log.info("开始初始化路由");
        List<Route> routeList = routeLocator.getRoutes().collectList().block();
        if(routeList == null){
            return;
        }
        routeList.forEach(routeDefinition -> {
            try{
                log.info("开始加载路由 [{}] ({})", routeDefinition.getId(), routeDefinition.getUri().toString());
                k8SServiceManager.getServiceAddress(routeDefinition.getId(), routeDefinition.getUri().toString());
            }catch (Exception e){
                log.error("无法加载路由 [{}] ({}) ==> {}", routeDefinition.getId(), routeDefinition.getUri().toString(),
                        e.getMessage());
            }

        });


    }
}
